<template>
	<view>
		<map
			id="googleMap"
			:latitude="latitude"
			:longitude="longitude"
			:scale="scale"
			:markers="markers"
			:polygons="polygons"
			@markertap="onMarkerTap"
		></map>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				latitude: 37.7749,
				longitude: -122.4194,
				scale: 13,
				markers: [],
				polygons: []
			}
		},
		onReady() {
			this.initPolygonFence();
		},
		methods: {
			initPolygonFence() {
				// 定义多边形的顶点坐标
				const polygonPoints = [
					{ latitude: 37.7749, longitude: -122.4194 },
					{ latitude: 37.7759, longitude: -122.4184 },
					{ latitude: 37.7749, longitude: -122.4174 },
					{ latitude: 37.7739, longitude: -122.4184 }
				];
	
				// 添加顶点标记
				polygonPoints.forEach((point, index) => {
					this.markers.push({
						id: index + 1,
						latitude: point.latitude,
						longitude: point.longitude,
						title: `顶点 ${index + 1}`
					});
				});
	
				// 添加多边形
				this.polygons.push({
					id: 1,
					points: polygonPoints,
					fillColor: 'rgba(0, 255, 0, 0.2)',
					strokeColor: 'rgba(0, 255, 0, 1)',
					strokeWidth: 2
				});
			},
			onMarkerTap(e) {
				console.log('Marker tapped:', e.markerId);
			},
			// 判断点是否在多边形内的算法（射线法）
			isPointInPolygon(point, polygon) {
				let inside = false;
				for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {
					const xi = polygon[i].latitude, yi = polygon[i].longitude;
					const xj = polygon[j].latitude, yj = polygon[j].longitude;
	
					const intersect = ((yi > point.longitude) !== (yj > point.longitude)) &&
						(point.latitude < (xj - xi) * (point.longitude - yi) / (yj - yi) + xi);
					if (intersect) inside = !inside;
				}
				return inside;
			},
			// 检测用户是否在多边形电子围栏内
			checkPolygonFence() {
				uni.getLocation({
					type: 'wgs84',
					success: (res) => {
						const userPoint = {
							latitude: res.latitude,
							longitude: res.longitude
						};
						const polygon = this.polygons[0].points;
						if (this.isPointInPolygon(userPoint, polygon)) {
							console.log('用户在多边形电子围栏内');
						} else {
							console.log('用户在多边形电子围栏外');
						}
					},
					fail: (err) => {
						console.error('获取位置失败:', err);
					}
				});
			}
		}
	}
</script>

<style>

</style>
